package sis.db;/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2019-07-30 09:57
 * @notify
 * @version 1.0
 */

import sis.dbtest.KeyFileTest;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class KeyFile {
    //存储 索引
    private Map<String, EntryData> keys = new HashMap<String, EntryData>();
    //文件
    private File file;
    //构造子接收一个文件名
    public KeyFile(String filename) throws IOException {
        //创建文件对象
        file = new File(filename);
        //如果文件存在
        if (file.exists()) {
            //读取文件
            load();
        }
    }

    //添加索引
    public void add(String key, long position, int length) {
        keys.put(key, new EntryData(position, length));
    }

    //返回索引长度
    public int size() {
        return keys.size();
    }

    //是否包含该索引
    public boolean containsKey(String key) {
        return keys.containsKey(key);
    }

    //获取指定索引的位置
    public long getPosition(String key) {
        return keys.get(key).getPosition();
    }

    //获取索引总长度
    public int getLength(String key) {
        return keys.get(key).getLength();
    }

    //将索引写入文件
    public void close() throws IOException {
        ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file));
        stream.writeObject(keys);
        stream.close();
    }

    //创建文件
    public void load() throws IOException {
        ObjectInputStream input = null;
        try {
            input = new ObjectInputStream((new FileInputStream(file)));
            try {
                //将读取到的数据 赋值给 map
                keys = (Map<String, EntryData>) input.readObject();
            } catch (ClassNotFoundException e) {
            }
        } finally {
            input.close();
        }
    }

    //登记数据
    public static class EntryData implements Serializable {
        //位置
        private long position;
        //长度
        private int length;

        //构造子
        public EntryData(long position, int length) {
            this.position = position;
            this.length = length;
        }

        //获取位置
        private long getPosition() {
            return position;
        }

        //获取长度
        private int getLength() {
            return length;
        }
    }
}
